<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\common\model\huntermanager\Hunter as HunterModel;
use app\common\model\MoneyLog;
use app\common\model\ads\Ad;
use think\Db;
use think\Config;
use fast\Random;

/**
 * 赏金猎人接口
 */
class Hunter extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *
     */
    public function index()
    {
        $this->success('', ['welcome' => '123']);
    }

    /*
     * 赏金猎人申请
     */
    public function hunterApply(){
        $user_id = $this->auth->getUserinfo()['id'];
        
        $item_num = User::where(array('top_id'=>$user_id))->count();    //推荐人数量
        
        $hunter_limit = config('site.hunter_limit');    //限制人数
        
        if($item_num < $hunter_limit){
            $this->error('需邀请'.$hunter_limit.'人,您还差'.($hunter_limit-$item_num).'人');
        }

        $where['user_id'] = $user_id;
        $allow_apply = HunterModel::where($where)->find();
        if($allow_apply){
            if($allow_apply['status'] == 0){
                $this->error('申请等待审核，请勿重复提交');
            }

            if($allow_apply['status'] == 1){
                $this->error('申请已审核通过，请勿重复提交');
            }

            if($allow_apply['status'] == 2){
                $allow_apply->delete();
            }
        }

        $data = $this->request->post();
        $data['user_id'] = $user_id;
        unset($data['token']);
        if(isset($data['share_from'])) unset($data['share_from']);

        $is_success = HunterModel::create($data);
        $this->success('提交成功,请等待审核', $is_success);
    }

    /*
     * 赏金猎人信息
     */
    public function getHunterInfo(){
        $user_id = $this->auth->getUserinfo()['id'];
        $where['user_id'] = $user_id;
        $where['status'] = array('in', '0, 1');
        $field = 'id, real_name, gender, province_id, city_id, county_id, age, mobile,
            createtime, user_id,status';
        $huter_info = HunterModel::where($where)->field($field)->find();
        if(!$huter_info) $huter_info = [];
        $huter_info['hunter_limit'] = config('site.hunter_limit');    //限制人数
        $this->success('赏金猎人信息', $huter_info);
    }

    /*
     * 我的团队
     */
    public function myTeam(){
        $user_id = $this->auth->id;
        // if(!HunterModel::isHunter($user_id)){
        //     $this->error('您还不是赏金猎人');
        // }
        
        $list = User::where(array('top_id'=>$user_id))->field('id,nickname,jointime,avatar')->order('jointime desc')->paginate()->each(function($item) use($user_id){
            $item->jointime_text = date('Y-m-d H:i', $item->jointime);
            $item->total_reward = MoneyLog::where('user_id', $user_id)->where('from_user_id', $item->id)->sum('money');
        });        

        $this->success('我的团队', $list);
    }

    
}
